<template>
  <view>
    <view
      class="floating-ball"
      :class="{ 'is-active': isActive }"
      :style="ballStyle"
      @touchstart="handleTouchStart"
      @touchmove="handleTouchMove"
      @touchend="handleTouchEnd"
    >
      <view class="ball-content">
        <uni-icons :type="isActive ? 'checkbox-filled' : 'checkbox'" size="24" color="#ffffff"></uni-icons>
      </view>
    </view>
    
    <info-popup
      ref="infoPopupRef"
      @save="handleInfoSave"
      @cancel="handleInfoCancel"
    />
  </view>
</template>

<script lang="ts" setup>
import { ref, computed } from 'vue';
import InfoPopup from '@/components/InfoPopup.vue';

// Props
const props = defineProps({
  initialPosition: {
    type: Object,
    default: () => ({ x: 20, y: 300 })
  }
});

// Emits
const emit = defineEmits(['stateChange', 'menuSelect']);

// State
const isActive = ref(false);
const position = ref(props.initialPosition);
const touchStartTime = ref(0);
const touchStartPos = ref({ x: 0, y: 0 });
const isTouching = ref(false);
const longPressTimer = ref<any>(null);
const popup = ref<any>(null);


// 计算样式
const ballStyle = computed(() => ({
  transform: `translate(${position.value.x}px, ${position.value.y}px)`,
  transition: isTouching.value ? 'none' : 'transform 0.3s ease'
}));

// 触摸事件处理
const handleTouchStart = (e: any) => {
  const touch = e.touches[0];
  touchStartTime.value = Date.now();
  touchStartPos.value = {
    x: touch.clientX - position.value.x,
    y: touch.clientY - position.value.y
  };
  isTouching.value = true;

  // 设置长按定时器
  longPressTimer.value = setTimeout(() => {
    showPopup();
  }, 500);
};

const handleTouchMove = (e: any) => {
  if (!isTouching.value) return;
  
  const touch = e.touches[0];
  const newX = touch.clientX - touchStartPos.value.x;
  const newY = touch.clientY - touchStartPos.value.y;
  
  // 获取屏幕尺寸
  const systemInfo = uni.getSystemInfoSync();
  const ballSize = uni.upx2px(80); // 将80rpx转换为px
  const maxX = systemInfo.windowWidth - ballSize;
  const maxY = systemInfo.windowHeight - ballSize;
  
  // 限制边界
  position.value = {
    x: Math.min(Math.max(0, newX), maxX),
    y: Math.min(Math.max(0, newY), maxY)
  };
  
  // 如果移动超过阈值，取消长按
  const moveDistance = Math.sqrt(
    Math.pow(touch.clientX - touchStartPos.value.x, 2) +
    Math.pow(touch.clientY - touchStartPos.value.y, 2)
  );
  
  if (moveDistance > 10) {
    clearTimeout(longPressTimer.value);
  }
};

const handleTouchEnd = (e: any) => {
  isTouching.value = false;
  clearTimeout(longPressTimer.value);
  
  // 判断是否为点击（时间小于200ms且移动距离小于10px）
  const touchEndTime = Date.now();
  const touchDuration = touchEndTime - touchStartTime.value;
  
  if (touchDuration < 200) {
    const touch = e.changedTouches[0];
    const moveDistance = Math.sqrt(
      Math.pow(touch.clientX - touchStartPos.value.x, 2) +
      Math.pow(touch.clientY - touchStartPos.value.y, 2)
    );
    
    if (moveDistance < 10) {
      toggleState();
    }
  }
  
  // 自动吸附到边缘
  snapToBorder();
};

// 状态切换
const toggleState = () => {
  isActive.value = !isActive.value;
  emit('stateChange', isActive.value);
};

// 边缘吸附
const snapToBorder = () => {
  const systemInfo = uni.getSystemInfoSync();
  const halfWidth = systemInfo.windowWidth / 2;
  
  // 判断是否需要吸附到左边还是右边
  const ballSize = uni.upx2px(80);
  position.value.x = position.value.x < halfWidth ? 0 : systemInfo.windowWidth - ballSize;
};

// 弹出菜单相关
const infoPopupRef = ref();
const showPopup = () => {
  infoPopupRef.value?.open();
};

const closePopup = () => {
  popup.value?.close();
};

const handleMenuClick = (item: any) => {
  emit('menuSelect', item.action);
  closePopup();
};

// 处理信息保存
const handleInfoSave = () => {
  uni.showToast({
    title: '信息已保存',
    icon: 'success'
  });
};

// 处理取消操作
const handleInfoCancel = () => {
  console.log('操作已取消');
};
</script>

<style lang="scss">
.floating-ball {
  position: fixed;
    width: 80rpx;
    height: 80rpx;
  border-radius: 50%;
  background: rgba(0, 0, 0, 0.6);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 999;
  will-change: transform;
  
  &.is-active {
    background: #07c160;
  }
  
  .ball-content {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    
    &:active {
      transform: scale(0.95);
    }
  }
}

.action-menu {
  background: #ffffff;
  border-radius: 20rpx;
  padding: 40rpx;
  width: 600rpx;
  box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.1);
  
  .menu-title {
    text-align: center;
    font-size: 32rpx;
    color: #333;
    margin-bottom: 30rpx;
  }
  
  .menu-items {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 20rpx;
    margin-bottom: 30rpx;
  }
  
  .menu-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 20rpx;
    
    text {
      margin-top: 10rpx;
      font-size: 24rpx;
      color: #333;
    }
    
    &:active {
      background: rgba(0, 0, 0, 0.05);
      border-radius: 10rpx;
    }
  }
  
  .menu-cancel {
    text-align: center;
    padding: 20rpx;
    color: #666;
    border-top: 1px solid #eee;
    
    &:active {
      background: rgba(0, 0, 0, 0.05);
    }
  }
}
</style>
